#! /usr/bin/env python
import sys
import os
import pygame
import math
import numpy as np
from pygame.locals import RLEACCEL
from constants import MAP_WIDTH, MAP_HEIGHT, TILE_SIZE

def load_image(name, colorkey=None):
    """
    Loads image from the image directory
    """
    fullname = os.path.join('..','images', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error as message:
        print('Cannot load image:', fullname)
        raise SystemExit(message)
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()

def load_sound_fx(name):
    """
    Loads sound from the sound directory
    """
    fullname = os.path.join('..','sounds',name)
    try:
        sound = pygame.mixer.Sound(fullname)
    except pygame.error as message:
        print('Failed to load sound fx:',fullname)
        raise SystemExit(message)
    return sound

def print_1d_map(map):
    height = MAP_HEIGHT//TILE_SIZE
    width = MAP_WIDTH//TILE_SIZE
    
    for y in range(height):
        print()
        for x in range(width):
            id = x + y*width
            test = map[id]
            print("{0}".format(test), end=' ')
    print()
    
def angleDifference( angle1, angle2 ):
    """
    Calculates the difference between two angles
    """
    diff = angle2 - angle1;
    while diff < -math.pi:
        diff = diff + 2*math.pi;
    while diff >= math.pi:
        diff = diff - 2*math.pi;
    return diff;
    
def get_base_path():
    """
    Return the absolute base path
    """
    print('Warning!: Called helpers.get_base_path. Method not implemented!')
    path_name = os.path.dirname(sys.argv[0])
    print(path_name)
    full_path = os.path.abspath(path_name)
    print(full_path[0])
    base_path = os.path.split(  full_path[0] )
    return base_path[0]

def rotate( vec, angle ):
    dcm = np.array([ [ math.cos(angle),  math.sin(angle)],
                     [-math.sin(angle), math.cos(angle)] ])
    return np.dot(dcm,vec)

def angle_between( vec1, vec2 ):
    tmp1 = np.vdot(vec1, vec2)
    tmp2 = np.linalg.norm( vec1 ) * np.linalg.norm( vec2 )
    
    if tmp2 == 0.0:
        return 0.0
    
    res = math.acos( tmp1 / tmp2 )
    return res

def truncate( vec, val ):
    '''
    Adjust a vector to a maximum length
    '''
    length = np.linalg.norm(vec)
    if length > val:
        vec = vec * val / length
    return vec